<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 轮胎管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <script src="/js/auth.js"></script>
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .navbar {
            background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .main-container {
            margin-top: 20px;
            padding: 20px;
        }
        .card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            margin-bottom: 20px;
        }
        .card-header {
            background: white;
            border-bottom: 1px solid #e3e6f0;
            padding: 20px;
            font-weight: 600;
        }
        .table th {
            border-top: none;
            font-weight: 600;
            color: #6c757d;
            background-color: #f8f9fa;
        }
        .badge-admin {
            background: linear-gradient(135deg, #dc3545, #e35d6a);
        }
        .badge-company {
            background: linear-gradient(135deg, #ffc107, #ffd54f);
        }
        .badge-driver {
            background: linear-gradient(135deg, #198754, #28a745);
        }
        .btn-add {
            background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
            border: none;
            color: white;
        }
        .switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 24px;
        }
        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 24px;
        }
        .slider:before {
            position: absolute;
            content: "";
            height: 16px;
            width: 16px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        input:checked + .slider {
            background-color: #28a745;
        }
        input:checked + .slider:before {
            transform: translateX(26px);
        }
        .modal-header {
            background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
            color: white;
        }
        .required::after {
            content: " *";
            color: #dc3545;
        }
        .password-note {
            font-size: 0.875rem;
            color: #6c757d;
            margin-top: 0.25rem;
        }
    </style>
</head>
<body>
<!-- 导航栏 -->
<nav class="navbar navbar-expand-lg navbar-dark">
    <div class="container-fluid">
        <a class="navbar-brand" href="#">
            <i class="fas fa-tire me-2"></i>
            轮胎管理系统
        </a>
        <div class="navbar-nav ms-auto">
            <div class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
                   data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="fas fa-user me-1"></i>
                    <span id="currentUser">管理员</span>
                </a>
                <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                    <li><a class="dropdown-item" href="#" onclick="logout()"><i class="fas fa-sign-out-alt me-2"></i>退出登录</a></li>
                </ul>
            </div>
        </div>
    </div>
</nav>

<div class="container-fluid main-container">
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-users me-2"></i>用户管理</h5>
            <button class="btn btn-add" onclick="showAddUserModal()">
                <i class="fas fa-plus me-2"></i>添加用户
            </button>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>角色</th>
                        <th>运输公司</th>
                        <th>车牌号</th>
                        <th>状态</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="userTableBody">
                    <!-- 用户数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 添加用户模态框 -->
<div class="modal fade" id="addUserModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加用户</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addUserForm">
                    <div class="mb-3">
                        <label class="form-label required">用户名</label>
                        <input type="text" class="form-control" id="addUsername" required>
                        <div class="invalid-feedback">请输入用户名</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label required">密码</label>
                        <input type="password" class="form-control" id="addPassword" required minlength="6">
                        <div class="invalid-feedback">密码长度不能少于6位</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label required">确认密码</label>
                        <input type="password" class="form-control" id="addConfirmPassword" required>
                        <div class="invalid-feedback">两次输入的密码不一致</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label required">角色</label>
                        <select class="form-select" id="addRole" required onchange="onRoleChange('add')">
                            <option value="">请选择角色</option>
                            <option value="DRIVER">司机</option>
                            <option value="COMPANY">运输公司</option>
                            <option value="ADMIN">管理员</option>
                        </select>
                        <div class="invalid-feedback">请选择角色</div>
                    </div>
                    <div class="mb-3" id="addTransportCompanyGroup" style="display: none;">
                        <label class="form-label">运输公司</label>
                        <input type="text" class="form-control" id="addTransportCompany">
                    </div>
                    <div class="mb-3" id="addVehiclePlateGroup" style="display: none;">
                        <label class="form-label">车牌号</label>
                        <input type="text" class="form-control" id="addVehiclePlateNumber">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="addUser()" id="addUserBtn">
                    <span id="addUserText">确定</span>
                    <span class="spinner-border spinner-border-sm d-none" id="addUserSpinner"></span>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑用户模态框 -->
<div class="modal fade" id="editUserModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑用户</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editUserForm">
                    <input type="hidden" id="editUserId">
                    <div class="mb-3">
                        <label class="form-label required">用户名</label>
                        <input type="text" class="form-control" id="editUsername" readonly>
                        <div class="form-text">用户名不可修改</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">角色</label>
                        <input type="text" class="form-control" id="editRoleDisplay" readonly>
                        <div class="form-text">角色不可修改</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">密码</label>
                        <input type="password" class="form-control" id="editPassword" placeholder="留空表示不修改密码" minlength="6">
                        <div class="password-note">留空表示不修改密码，最小长度为6位</div>
                        <div class="invalid-feedback">密码长度不能少于6位</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">确认密码</label>
                        <input type="password" class="form-control" id="editConfirmPassword" placeholder="留空表示不修改密码">
                        <div class="invalid-feedback">两次输入的密码不一致</div>
                    </div>
                    <div class="mb-3" id="editTransportCompanyGroup">
                        <label class="form-label">运输公司</label>
                        <input type="text" class="form-control" id="editTransportCompany">
                    </div>
                    <div class="mb-3" id="editVehiclePlateGroup">
                        <label class="form-label">车牌号</label>
                        <input type="text" class="form-control" id="editVehiclePlateNumber">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="updateUser()" id="editUserBtn">
                    <span id="editUserText">保存</span>
                    <span class="spinner-border spinner-border-sm d-none" id="editUserSpinner"></span>
                </button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    let users = [];
    let currentEditUserId = null;

    document.addEventListener('DOMContentLoaded', function() {
        checkAuth();
        loadUsers();
        displayCurrentUser();
    });

    function checkAuth() {
        const token = localStorage.getItem('token');
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');

        // 调试信息
        console.log('检查认证状态:');
        console.log('Token:', token);
        console.log('用户信息:', userInfo);

        if (!token || !userInfo.username) {
            console.log('未登录，跳转到登录页');
            window.location.href = '/login';
            return;
        }

        if (userInfo.role !== 'ADMIN') {
            console.log('权限不足，用户角色:', userInfo.role);
            alert('权限不足');
            window.location.href = '/dashboard';
            return;
        }

        console.log('认证通过，用户角色:', userInfo.role);
    }

    function displayCurrentUser() {
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
        document.getElementById('currentUser').textContent = userInfo.username || '用户';
    }

    async function loadUsers() {
        try {
            console.log('开始加载用户列表...');

            const response = await fetch('/api/users', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'include'
            });

            console.log('响应状态:', response.status);

            if (response.ok) {
                const data = await response.json();
                console.log('获取到的用户数据:', data);
                users = data;
                renderUserTable();
            } else {
                // 尝试获取错误信息
                let errorMessage = '未知错误';
                try {
                    const errorData = await response.json();
                    errorMessage = errorData.message || errorMessage;
                } catch (e) {
                    errorMessage = response.statusText;
                }

                console.error('API 错误响应:', errorMessage);

                if (response.status === 401) {
                    alert('登录已过期，请重新登录');
                    localStorage.removeItem('token');
                    localStorage.removeItem('userInfo');
                    window.location.href = '/login';
                } else if (response.status === 403) {
                    alert('权限不足，无法访问用户管理。请确保您以管理员身份登录。');
                    // 显示当前用户信息用于调试
                    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                    console.log('当前用户信息:', userInfo);
                } else {
                    throw new Error(`加载用户列表失败: ${response.status} - ${errorMessage}`);
                }
            }
        } catch (error) {
            console.error('Error loading users:', error);

            // 更详细的错误信息
            if (error.message.includes('Failed to fetch')) {
                alert('网络连接失败，请检查网络连接或后端服务是否正常运行');
            } else {
                alert(error.message || '加载用户列表失败，请检查控制台获取详细信息');
            }
        }
    }

    // 修改 renderUserTable 函数中的角色显示部分
    function renderUserTable() {
        const tbody = document.getElementById('userTableBody');

        // 添加 null 检查
        if (!tbody) {
            console.error('错误: 找不到 ID 为 "userTableBody" 的表格体元素');
            return;
        }

        tbody.innerHTML = '';

        if (users.length === 0) {
            tbody.innerHTML = `
        <tr>
          <td colspan="8" class="text-center py-4">
            <div class="text-muted">
              <i class="fas fa-users fa-2x mb-3"></i>
              <p>暂无用户数据</p>
            </div>
          </td>
        </tr>
      `;
            return;
        }

        users.forEach(user => {
            const row = document.createElement('tr');

            // 处理角色显示
            const roleDisplay = getRoleName(user.role);
            const roleBadgeClass = getRoleBadgeClass(user.role);

            row.innerHTML = `
        <td>${user.id}</td>
        <td>${user.username}</td>
        <td><span class="badge ${roleBadgeClass}">${roleDisplay}</span></td>
        <td>${user.transportCompany || '-'}</td>
        <td>${user.vehiclePlateNumber || '-'}</td>
        <td>
          <label class="switch">
            <input type="checkbox" ${user.enabled ? 'checked' : ''} onchange="toggleUserStatus(${user.id}, this.checked)">
            <span class="slider"></span>
          </label>
        </td>
        <td>${formatDate(user.createdTime)}</td>
        <td>
          <button class="btn btn-sm btn-outline-primary me-1" onclick="editUser(${user.id})">
            <i class="fas fa-edit"></i>
          </button>
          <button class="btn btn-sm btn-outline-danger" onclick="deleteUser(${user.id})">
            <i class="fas fa-trash"></i>
          </button>
        </td>
      `;
            tbody.appendChild(row);
        });
    }

    // 修改 getRoleBadgeClass 函数，移除对 UserRole 的引用
    function getRoleBadgeClass(role) {
        // 处理枚举对象或字符串
        let roleValue;
        if (typeof role === 'object' && role !== null) {
            // 如果是对象，尝试获取 name 属性或直接转换为字符串
            roleValue = role.name || role.toString();
        } else {
            // 如果是字符串，直接使用
            roleValue = role;
        }

        // 现在 roleValue 应该是字符串
        switch (roleValue) {
            case 'ADMIN':
                return 'badge-admin';
            case 'COMPANY':
                return 'badge-company';
            case 'DRIVER':
                return 'badge-driver';
            default:
                return 'badge-secondary';
        }
    }

    // 修改 getRoleName 函数，移除对 UserRole 的引用
    function getRoleName(role) {
        // 处理枚举对象或字符串
        let roleValue;
        if (typeof role === 'object' && role !== null) {
            // 如果是对象，尝试获取 name 属性或直接转换为字符串
            roleValue = role.name || role.toString();
        } else {
            // 如果是字符串，直接使用
            roleValue = role;
        }

        // 现在 roleValue 应该是字符串
        switch (roleValue) {
            case 'ADMIN':
                return '管理员';
            case 'COMPANY':
                return '运输公司';
            case 'DRIVER':
                return '司机';
            default:
                return roleValue || '未知角色';
        }
    }

    function formatDate(dateString) {
        if (!dateString) return '-';
        try {
            return new Date(dateString).toLocaleString('zh-CN');
        } catch (e) {
            return dateString;
        }
    }

    function showAddUserModal() {
        const modal = new bootstrap.Modal(document.getElementById('addUserModal'));
        document.getElementById('addUserForm').reset();
        document.getElementById('addTransportCompanyGroup').style.display = 'none';
        document.getElementById('addVehiclePlateGroup').style.display = 'none';

        // 清除验证状态
        const form = document.getElementById('addUserForm');
        form.classList.remove('was-validated');

        modal.show();
    }

    function onRoleChange(type) {
        const role = document.getElementById(type === 'edit' ? 'editRole' : 'addRole').value;
        const transportCompanyGroup = document.getElementById(type === 'edit' ? 'editTransportCompanyGroup' : 'addTransportCompanyGroup');
        const vehiclePlateGroup = document.getElementById(type === 'edit' ? 'editVehiclePlateGroup' : 'addVehiclePlateGroup');

        if (type === 'add') {
            transportCompanyGroup.style.display = (role === 'DRIVER' || role === 'COMPANY') ? 'block' : 'none';
            vehiclePlateGroup.style.display = (role === 'DRIVER') ? 'block' : 'none';
        }
    }

    // 修改 addUser 函数，确保发送正确的数据格式
    async function addUser() {
        const form = document.getElementById('addUserForm');
        const username = document.getElementById('addUsername').value.trim();
        const password = document.getElementById('addPassword').value;
        const confirmPassword = document.getElementById('addConfirmPassword').value;
        const role = document.getElementById('addRole').value;
        const transportCompany = document.getElementById('addTransportCompany').value.trim();
        const vehiclePlateNumber = document.getElementById('addVehiclePlateNumber').value.trim();

        // 表单验证
        form.classList.add('was-validated');

        if (!form.checkValidity()) {
            return;
        }

        if (password !== confirmPassword) {
            alert('两次输入的密码不一致');
            document.getElementById('addConfirmPassword').focus();
            return;
        }

        if (password.length < 6) {
            alert('密码长度不能少于6位');
            document.getElementById('addPassword').focus();
            return;
        }

        try {
            setAddUserLoading(true);

            // 创建用户数据对象
            const userData = {
                username: username,
                password: password,
                role: role, // 这里发送的是字符串，如 "ADMIN", "COMPANY", "DRIVER"
                transportCompany: transportCompany || null,
                vehiclePlateNumber: vehiclePlateNumber || null
            };

            console.log('正在创建用户:', userData);

            const response = await fetch('/api/users', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
                body: JSON.stringify(userData)
            });

            console.log('添加用户响应状态:', response.status);

            if (response.ok) {
                const newUser = await response.json();
                console.log('创建用户成功:', newUser);

                const modal = bootstrap.Modal.getInstance(document.getElementById('addUserModal'));
                modal.hide();
                alert('添加用户成功');
                loadUsers(); // 重新加载用户列表
            } else {
                const errorData = await response.json();
                console.error('添加用户错误:', errorData);
                throw new Error(errorData.message || `添加用户失败: ${response.status}`);
            }
        } catch (error) {
            console.error('Error adding user:', error);
            alert(error.message || '添加用户失败');
        } finally {
            setAddUserLoading(false);
        }
    }

    function setAddUserLoading(loading) {
        const btn = document.getElementById('addUserBtn');
        const text = document.getElementById('addUserText');
        const spinner = document.getElementById('addUserSpinner');

        if (loading) {
            btn.disabled = true;
            text.classList.add('d-none');
            spinner.classList.remove('d-none');
        } else {
            btn.disabled = false;
            text.classList.remove('d-none');
            spinner.classList.add('d-none');
        }
    }

    // 编辑用户功能
    function editUser(userId) {
        const user = users.find(u => u.id === userId);
        if (!user) {
            alert('用户不存在');
            return;
        }

        currentEditUserId = userId;

        // 填充表单数据
        document.getElementById('editUserId').value = user.id;
        document.getElementById('editUsername').value = user.username;
        document.getElementById('editRoleDisplay').value = getRoleName(user.role);
        document.getElementById('editPassword').value = '';
        document.getElementById('editConfirmPassword').value = '';
        document.getElementById('editTransportCompany').value = user.transportCompany || '';
        document.getElementById('editVehiclePlateNumber').value = user.vehiclePlateNumber || '';

        // 根据角色显示/隐藏相关字段
        const role = user.role;
        if (typeof role === 'object') {
            roleValue = role.name || role.toString();
        } else {
            roleValue = role;
        }

        const transportCompanyGroup = document.getElementById('editTransportCompanyGroup');
        const vehiclePlateGroup = document.getElementById('editVehiclePlateGroup');

        // 管理员不显示运输公司和车牌号字段
        if (roleValue === 'ADMIN') {
            transportCompanyGroup.style.display = 'none';
            vehiclePlateGroup.style.display = 'none';
        } else {
            transportCompanyGroup.style.display = 'block';
            vehiclePlateGroup.style.display = roleValue === 'DRIVER' ? 'block' : 'none';
        }

        // 清除验证状态
        const form = document.getElementById('editUserForm');
        form.classList.remove('was-validated');

        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('editUserModal'));
        modal.show();
    }

    // 更新用户信息
    async function updateUser() {
        const form = document.getElementById('editUserForm');
        const password = document.getElementById('editPassword').value;
        const confirmPassword = document.getElementById('editConfirmPassword').value;
        const transportCompany = document.getElementById('editTransportCompany').value.trim();
        const vehiclePlateNumber = document.getElementById('editVehiclePlateNumber').value.trim();

        // 密码验证
        if (password && password.length < 6) {
            alert('密码长度不能少于6位');
            document.getElementById('editPassword').focus();
            return;
        }

        if (password !== confirmPassword) {
            alert('两次输入的密码不一致');
            document.getElementById('editConfirmPassword').focus();
            return;
        }

        try {
            setEditUserLoading(true);

            // 创建更新数据对象
            const updateData = {
                transportCompany: transportCompany || null,
                vehiclePlateNumber: vehiclePlateNumber || null
            };

            // 如果密码不为空，则更新密码
            if (password) {
                updateData.password = password;
            }

            console.log('正在更新用户:', updateData);

            const response = await fetch(`/api/users/${currentEditUserId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
                body: JSON.stringify(updateData)
            });

            console.log('更新用户响应状态:', response.status);

            if (response.ok) {
                const updatedUser = await response.json();
                console.log('更新用户成功:', updatedUser);

                const modal = bootstrap.Modal.getInstance(document.getElementById('editUserModal'));
                modal.hide();
                alert('更新用户成功');
                loadUsers(); // 重新加载用户列表
            } else {
                const errorData = await response.json();
                console.error('更新用户错误:', errorData);
                throw new Error(errorData.message || `更新用户失败: ${response.status}`);
            }
        } catch (error) {
            console.error('Error updating user:', error);
            alert(error.message || '更新用户失败');
        } finally {
            setEditUserLoading(false);
        }
    }

    function setEditUserLoading(loading) {
        const btn = document.getElementById('editUserBtn');
        const text = document.getElementById('editUserText');
        const spinner = document.getElementById('editUserSpinner');

        if (loading) {
            btn.disabled = true;
            text.classList.add('d-none');
            spinner.classList.remove('d-none');
        } else {
            btn.disabled = false;
            text.classList.remove('d-none');
            spinner.classList.add('d-none');
        }
    }

    async function toggleUserStatus(userId, enabled) {
        try {
            const response = await fetch(`/api/users/${userId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'include', // 确保发送 session cookie
                body: JSON.stringify({ enabled: enabled })
            });

            if (response.ok) {
                alert('状态更新成功');
                loadUsers(); // 刷新列表
            } else {
                const errorData = await response.json();
                throw new Error(errorData.message || '更新用户状态失败');
            }
        } catch (error) {
            console.error('Error updating user status:', error);
            alert(error.message || '状态更新失败');
            loadUsers(); // 重新加载以恢复原始状态
        }
    }

    async function deleteUser(userId) {
        const user = users.find(u => u.id === userId);
        if (!user) return;

        if (!confirm(`确定要删除用户 "${user.username}" 吗？此操作不可恢复。`)) {
            return;
        }

        try {
            const response = await fetch(`/api/users/${userId}`, {
                method: 'DELETE',
                credentials: 'include' // 确保发送 session cookie
            });

            if (response.ok) {
                alert('删除用户成功');
                loadUsers();
            } else {
                const errorData = await response.json();
                throw new Error(errorData.message || '删除用户失败');
            }
        } catch (error) {
            console.error('Error deleting user:', error);
            alert(error.message || '删除用户失败');
        }
    }

    async function logout() {
        try {
            // 调用后端登出接口
            await fetch('/api/auth/logout', {
                method: 'POST',
                credentials: 'include' // 确保发送 session cookie
            });
        } catch (error) {
            console.error('Logout error:', error);
        } finally {
            // 清除前端存储
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            window.location.href = '/login';
        }
    }

    // 添加调试函数来检查用户数据
    function debugUserData() {
        console.log('当前用户数据:', users);
        if (users.length > 0) {
            console.log('第一个用户的角色信息:', {
                raw: users[0].role,
                type: typeof users[0].role,
                stringValue: users[0].role ? users[0].role.toString() : 'null',
                name: users[0].role ? users[0].role.name : 'null'
            });
        }
    }
</script>
</body>
</html>